<template>
	<div class="app-container">
		<el-form :model="form" :rules="rules" ref="queryRef" :inline="true" label-width="106px">
			<div class="bgWhite radius8">
				<div class=" fb fs16 border-bottom pl30 line-64">
					商品详情
				</div>
				<div class="p20">
					<div class="fb mb20 pl10">
						基础信息
					</div>
					<el-form-item label="商品类型：" prop="commodityType">
						<div class="item-width">
							<dict-tag :options="bus_product_type" :value="form.commodityType" />
						</div>
					</el-form-item>
					<el-form-item label="关联产品：" prop="productId" v-if="form.commodityType != 1003">
						<div class="item-width">
							{{form.productName}}
						</div>
					</el-form-item>
					<el-form-item label="商品名称：" prop="commodityName">
						<div class="item-width">
							{{form.commodityName}}
						</div>
					</el-form-item>
					<el-form-item label="商品ID：" prop="commodityCode">
						<div class="item-width">
							{{form.commodityCode}}
						</div>
						<!-- <el-input size="large" v-model="form.commodityCode" style="width: 248px" placeholder="请填写" /> -->
					</el-form-item>
					<el-form-item label="最小单位：" prop="minUnit">
						<div class="item-width">
							{{form.minUnit}}
						</div>
						<!-- <el-input size="large" v-model="form.minUnit" style="width: 248px" placeholder="请填写" /> -->
					</el-form-item>
					<el-form-item label="商品单价：" prop="caseQuantity" v-if="form.commodityType == 1003">
						<div class="item-width">
							{{form.caseQuantity}}
						</div>
						<!-- <el-input size="large" v-model="form.caseQuantity" style="width: 248px" placeholder="请填写" /> -->
					</el-form-item>
					<el-form-item label="整件数量：" prop="caseQuantity">
						<div class="item-width">
							{{form.caseQuantity}}
						</div>
						<!-- <el-input size="large" v-model="form.caseQuantity" style="width: 248px" placeholder="请填写" /> -->
					</el-form-item>
					<el-form-item label="单位含量：" prop="unitContent" v-if="form.commodityType != 1003">
						<div class="item-width flex col-center">
							{{form.unitContent}}<dict-tag :options="bus_active_ingredient_content" :value="form.contentUnit" />
						</div>
					</el-form-item>
					<el-form-item label="商品规格：" prop="specificationId">
						<div class="item-width">
							<dict-tag :options="bus_product_specification_unit" :value="form.specificationId" />
						</div>
					</el-form-item>
					<el-form-item label="商品分类：" prop="classifyId" >
						<div>
							{{form.classifyName}}
						</div>
					</el-form-item>
					<br>
					<el-form-item label="产品宣传图：" prop="mainImageUrl" style="width: 350px;">
						<img v-if="form.mainImageUrl" :src="form.mainImageUrl"
							style="width: 110px;height: 110px;" />
					</el-form-item>
					<br>
					<el-form-item label="备注信息：" prop="remark" label-width="106" v-if="form.commodityType == 1003">
						<el-input readonly size="large" type="textarea" resize="none" class="textReset" style="width: 575px;"
							:rows="5" v-model="form.remark" placeholder="请输入信息" />
					</el-form-item>
				</div>
				<div class="pl20 pr20" v-if="form.commodityType != 1003">
					<div class="fb mb20 pl10">
						线上渠道价格
					</div>
					<el-form-item label="拆箱单价(元)" prop="onlineUnitPrice">
						<div class="item-width">
							{{form.onlineUnitPrice}}
						</div>
						<!-- <el-input size="large" v-model="form.onlineUnitPrice" style="width: 246px" placeholder="请填写" /> -->
					</el-form-item>
					<el-form-item label="整件单价(元)" prop="caseUnitPrice">
						<div class="item-width">
							{{form.caseUnitPrice}}
						</div>
						<!-- <el-input size="large" v-model="form.caseUnitPrice" style="width: 246px" placeholder="请填写" /> -->
					</el-form-item>
					<el-form-item label="吨位(元)" prop="tonPrice">
						<div class="item-width">
							{{form.tonPrice}}
						</div>
						<!-- <el-input size="large" v-model="form.tonPrice" style="width: 248px" placeholder="请填写" /> -->
					</el-form-item>
				</div>
				<div class="p20" v-if="form.commodityType != 1003">
					<div class="fb mb20 pl10 flex col-center row-between">
						线下渠道价格
						<!-- <el-button type="defaultBtn" @click="handleAdd"
						>新增
						</el-button> -->
					</div>
					<el-table :data="form.offlinePrices" style="width: 100%;"
						:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}"
						:cell-style="{height:'54px'}">
						<el-table-column label="出厂价格（元/最小单位）" align="center" width="250px">
							<template #default="scope">
								<div class="item-width">
									{{scope.row.factoryPrice}}
								</div>
								<!-- <el-input v-model="scope.row.factoryPrice" style="width: 120px" size="large"
									placeholder="请输入" /> -->
							</template>
						</el-table-column>
						<el-table-column label="定制价格（元/最小单位）" align="center" width="250px">
							<template #default="scope">
								<div class="item-width">
									{{scope.row.customPrice}}
								</div>
								<!-- <el-input v-model="scope.row.customPrice" style="width: 120px" size="large"
									placeholder="请输入" /> -->
							</template>
						</el-table-column>
						<el-table-column label="吨位（元/吨）" align="center" width="250px">
							<template #default="scope">
								<div class="item-width">
									{{scope.row.tonPrice}}
								</div>
								<!-- <el-input v-model="scope.row.tonPrice" style="width: 120px" size="large"
									placeholder="请输入" /> -->
							</template>
						</el-table-column>
						<el-table-column label="应用范围" align="center">
							<template #default="scope">
								<div class="flex col-center">
									此规则应用范围：
									<div v-if="scope.$index == 0">
										此规则应用范围：全部部门（特殊部门除外）
									</div>
									<el-tree-select v-else disabled size="large" v-model="scope.row.departmentIds1" :data="deptOptions"
									:multiple="true"
									@node-click="changeTree"
									 :props="{
									   value: 'deptId',
									   label: 'deptName',
									   children: 'children',
									}"  placeholder="请选择" 
									value-key="deptId"
									show-checkbox
									 @check-change="handleCheckChange"
									 style="width: 400px;"
									 />
								</div>
							</template>
						</el-table-column>
						<!-- <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width"
							width="250px">
							<template #default="scope">
								<span class="color-red cursor"
									@click="del(scope.$index)">删除</span>
							</template>
						</el-table-column> -->
					</el-table>
					<br>
					<el-form-item label="备注信息：" prop="remark" label-width="106">
						<div style="width: 575px;line-height: 25px;padding-top: 8px;">
							{{form.remark}}
						</div>
					</el-form-item>
				</div>
				
			</div>
		</el-form>
		<!-- 产品弹窗 -->
		<productList ref="dialog" @productIds="productIds"></productList>
	</div>
</template>

<script setup name="addCustomer">
	const {
		proxy
	} = getCurrentInstance();
	const {
		bus_product_type, //产品类型
		bus_product_category, //产品类别
		bus_toxicity, //毒性
		bus_sosage_form, //剂型
		bus_control_object, //防治对象
		bus_application_mode, //施用方式
		bus_target, //靶标
		bus_channel, //渠道
		bus_active_ingredient_content, //单位
		bus_product_specification_unit//规格
	} =
	proxy.useDict(
		"bus_product_type",
		"bus_product_category",
		"bus_toxicity",
		"bus_sosage_form",
		"bus_control_object",
		"bus_application_mode",
		"bus_target",
		"bus_channel",
		"bus_active_ingredient_content",
		"bus_product_specification_unit"
		);
</script>
<script>
	import {
		listGoods, //商品列表
		addGoods,//添加商品
		getGoods, //商品详情
		updateGoods, //修改商品
		listProduct,//产品列表
		listClassify1
	} from "@/api/business/product";
	import {
		getCustomerDetail
	} from "@/api/business/customer";
	import {
		getDivisions
	} from "@/api/business/opportunity";
	import {
		getOpportunityInfo,
		listOpportunity,
		teamAllocation,
		teamReceive,
		getUserListData
	} from "@/api/business/teamOpportunity";
	import {
	   listDept,//査部门
	} from "@/api/system/dept";
	import {
		resetForm,
		getUserInfo
	} from '@/utils/ruoyi'
	import {
		getToken
	} from "@/utils/auth";
	let url = import.meta.env.VITE_APP_BASE_API + "/common/upload"
	let id = 0;
	import productList from "./components/index.vue"
	export default {
		components:{
			productList
		},
		data() {
			return {
				headers: {
					Authorization: 'Bearer ' + getToken() 
				},
				url: url,
				cateOptions:[],
				form: {
					id: '',
					classifyId: '',
					commodityType: '', //产品类型
					productId: '', //关联产品id
					specificationId: '', //
					commodityName: '', //商品名称
					commodityCode: '', //商品id
					commodityPublic: '', //是否公海0=正常1=部门公海2=公司公海
					minUnit: '', //最小单位
					caseQuantity: '', //整件数量
					unitContent: '', //单位含量
					contentUnit: '', //含量单位
					mainImageUrl: '', //商品主图
					onlineUnitPrice: '', //线上拆箱单价
					caseUnitPrice: '', //整箱单价
					tonPrice: '', //吨价
					offlinePrices: [{
						factoryPrice: '', //出厂价格
						customPrice: '', //定制价格
						tonPrice: '', //吨价
						departmentIds:0, //应用范围（部门ID，逗号分隔）0代表全部
						departmentIds1:0,
						remark: '', //备注
					}],
					remark: '', //备注
				},
				rules: {
					commodityName: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}],
					caseQuantity: [{
						required: true,
						message: '请输入整件数量',
						trigger: 'blur'
					}],
					onlineUnitPrice: [{
						required: true,
						message: '请输入拆箱单价',
						trigger: 'blur'
					}],
					caseUnitPrice: [{
						required: true,
						message: '请输入整件单价',
						trigger: 'blur'
					}],
					tonPrice: [{
						required: true,
						message: '请输入吨位',
						trigger: 'blur'
					}],
					specificationId:[
						{
							required: true,
							message: '请输入商品规格',
							trigger: 'blur'
						}
					]
				},
				list: [],
				loading: false,
				deptOptions: [], //部门
				cropNameArr: [], //作物名称
				productList: [], //产品名称
				options: [],
				value: [],
				loading1: false,
			}
		},
		created() {
			this.form.id = this.$route.query.id ? this.$route.query.id : ''
			if (this.form.id != '') {
				const obj = Object.assign({}, this.$route, {
					title: "编辑商品"
				});
				this.$tab.updatePage(obj);
				//获取详情
				this.listGoods()
				
			} else {
				const obj = Object.assign({}, this.$route, {
					title: "新增商品"
				});
				this.$tab.updatePage(obj);
			}
			
		},
		methods: {
			getTree() {
				listClassify1().then(res => {
					if (res.code == 200) {
						let dataArr = res.data
						for (let key in dataArr) {
							dataArr[key].label = dataArr[key].name
						}
						for(let key in dataArr){
							if(dataArr[key].id == this.form.classifyId){
								this.form.classifyName = dataArr[key].name
							}
						}
						// this.cateOptions = this.handleTree(dataArr)
					}
				})
			},
			productIds(e){
				
			},
			// 关联产品
			chooseProduct(){
				this.$refs.dialog.open()
			},
			getProduct(){
				listProduct().then(res => {
					this.options = res.rows
					for(let key in this.options){
						if(this.form.productId == this.options[key].id){
							this.form.productName = this.options[key].productName
						}
					}
				})
			},
			remoteMethod(query) {
				if (query !== '') {
					this.loading = true;
					listProduct({
						keyword: query
					}).then(res => {
						this.options = res.rows
						this.loading1 = false;
					})
				} else {
					this.options = [];
				}
			},
			listGoods(){
				listGoods().then(res => {
					this.options = res.rows
					this.getDetail()
				})
			},
			closePage() {
				this.$tab.closePage();
			},
			// 重置
			resetQuery() {
				this.resetForm("queryRef");
				// console.log(this.form,'quer===')
			},
			// 详情
			getDetail() {
				getGoods(this.form.id).then(res => {
					this.form = res.data
					if(this.form.offlinePrices.length == 0){
						this.form.offlinePrices.push({
							factoryPrice: '', //出厂价格
							customPrice: '', //定制价格
							tonPrice: '', //吨价
							departmentIds: [], //应用范围（部门ID，逗号分隔）0代表全部
							departmentIds1:[],
							remark: '', //备注
						})
					}else{
						
						for(let key in this.form.offlinePrices){
							this.form.offlinePrices[key].departmentIds1 = this.form.offlinePrices[key].departmentIds ? this.form.offlinePrices[key].departmentIds.split(',') : []
							// if(this.form.offlinePrices[key].departmentIds1.length > 0){
							// 	this.form.offlinePrices[key].departmentIds1 = this.form.offlinePrices[key].departmentIds.split(',')
							// }else{
							// 	this.form.offlinePrices[key].departmentIds1 = []
							// }
						}
					}
					//获取部门
					this.getUserList()
					//获取产品
					this.getProduct()
					//获取分类树
					this.getTree()
				})
			},
			handleAvatarSuccess(e) {
				this.form.mainImageUrl = e.url
			},
			beforeAvatarUpload(e) {
				console.log(e, 'e2')
			},
			//添加
			submitProduct(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if(this.form.offlinePrices.length > 0){
							for(let key in this.form.offlinePrices){
								if(this.form.offlinePrices[key].departmentIds1.length > 0){
									this.form.offlinePrices[key].departmentIds = this.form.offlinePrices[key].departmentIds1.length == 1 ? 0 : this.form.offlinePrices[key].departmentIds1.join(',')
								}else{
									this.form.offlinePrices[key].departmentIds = ''
								}
							}
						}
						// 新增
						if (this.form.id == '') {
							addGoods(this.form).then(response => {
								this.$message({
									message: '添加成功',
									type: 'success'
								});
								setTimeout(() => {
									this.$router.go(-1)
								}, 1500)
							})
						} else {
							// 编辑
							updateGoods(this.form).then(response => {
								this.$message({
									message: '编辑成功',
									type: 'success'
								});
								setTimeout(() => {
									this.$router.go(-1)
								}, 1500)
							})
						}
					} else {
						return false;
					}
				});
			},


			// 删除
			del(index) {
				this.form.offlinePrices.splice(index, 1);
			},
			// 获取部门
			getUserList() {
				listDept().then((response) => {
				   this.deptOptions = this.handleTree(response.data, "deptId");
				});
			},
			handleAdd() {
				let item = {
					factoryPrice: '', //出厂价格
					customPrice: '', //定制价格
					tonPrice: '', //吨价
					departmentIds: [], //应用范围（部门ID，逗号分隔）0代表全部
					departmentIds1:[],
					remark: '', //备注
				}
				this.form.offlinePrices.push(item)
			}
		}
	}
</script>

<style>
	.item-width{
		width: 248px;
	}
	.el-form-item--default .el-form-item__label{
		color: #8c939d;
		font-weight: normal;
	}
	.avatar-uploader .el-upload {
		background: #F7F8FA;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 110px;
		height: 110px;
		text-align: center;
		line-height: 22px;
		color: #8c939d;
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		text-align: center;
	}

	.shopImg {
		width: 110px;
		height: 110px;
	}
</style>